%-------------PORTFOLIO OPTIMIZATION FUNCTION UNDER CVAR MINIMIZATION----
%
function [fval,w]=CVaROptimization(ScenRets,w0, R0, VaR0, beta,  UB, LB)
%
%
% The function estimates the optimal portfolio weights that minimize CVaR
% under a given target return R0
%该函数估计在给定目标收益率R0下使CVaR最小化的最优投资组合权重
%INPUTS: ScenRets: Portfolio returns matrix
%       R0: The target return
%       beta:The confidence level between 0.9 and 0.999
%       LB, UB the upper and lower bound for the optimal weights. For example If
%       you imput UB=.25 none of the stocks can consist more than the 25% of the
%       portfolio. 
%       VaR0= the initial guess for the portfolio VaR
%输入：ScenRets：投资组合回报矩阵
%       R0: 目标返回值
%       beta:置信度
%       LB, UB： 最优权重的上限和下限。例如，如果你输入UB=0.25，所有股票都不能超过投资组合的25%。
%       VaR0=投资组合VaR的初步猜测
%OUTPUTS: fval = CVaR of the optimal portfolio
%         w= the weights of the optimal portfolio, The last element in w
%         equals the VaR of the optimal portfolio
%输出: fval =最优投资组合的CVaR
%         w= 最优投资组合的权重，w中的最后一个元素等于最优投资组合的VaR
%---------------- INPUT ARGUMENTS--------------------------------------
% The function accepts 6 imputs however only the two first are required
% If you dont supply the 6 argument then LB=0 (no short positions)
% If you dont supply the 5 argument then UB=1
% If you dont supply the 4 argument then beta=0.95
% If you dont supply the 3 argument VaR0 equals the HS VaR of the equally weighted
% portfolio 
%---------------- 输入参数--------------------------------------
% 该函数接受6个输入，但前两个是必须的
% 如果你没有输入六个参数，那么LB=0
% 如果你没有输入五个参数，那么UB=0
%如果你没有输入四个参数，那么beta=0.95
% 如果你没有输入三个参数，那么VaR0等于权重相同的HS VaR
% portfolio 

% Author: Manthos Vogiatzoglou, Un of Macedonia, 20/08/2008
% contact: vogia@yahoo.com

[J, nAssets]=size(ScenRets);
%w0=[(1/nAssets)*ones(1,nAssets)];
if isempty(LB)
    LB=0;
end
if isempty(UB)
    UB=1;
end
if isempty(beta)
   beta=.95;
end
if isempty(VaR0)
   VaR0= quantile(ScenRets*w0',.95);
end
if beta>1||beta<0.9
    error('The confidence level beta = 1 - alpha, should be in (0.9 0.99)')
end
if LB>=UB
    error('The LB has to be smaller than UB')
end
if UB>1
    error('The upper bound should be less than 1')
end
if LB<-1
    error('The lower bound should be greater than -1')
end
i=1:nAssets;
% the objective function
%目标函数
Riskfun=@(w) w(nAssets+1)+(1/J)*(1/(1-beta))*sum(max(-w(i)*ScenRets(:,i)'-w(nAssets+1),0));
w0=[w0 VaR0];
% the (linear) equalities and unequalities matrixes
%等式不等式矩阵
A=[-mean(ScenRets) 0];
A=[A;  -eye(nAssets) zeros(nAssets,1)];
A=[A; eye(nAssets) zeros(nAssets,1)];
b=[-R0 -LB*ones(1,nAssets) UB*ones(1,nAssets)];
b=b';
Aeq=[ ones(1,nAssets) 0];
beq=[1];
options=optimset('LargeScale','off');
options=optimset(options,'Display','off');
options=optimset(options,'Algorithm','sqp');
options=optimset(options,'MaxFunEvals',5000);
% The VaR of the optimal portfolio equals w(nassets+1) 
%最优投资组合的VaR等于w（nassets+1）

[w,fval]=fmincon(Riskfun,w0,A,b,Aeq,beq,LB,UB,[],options);


